import React from 'react';
import { Form, Input, Select, Modal, Radio, Card, Checkbox, Button } from 'antd';
import styles from '../../style.less';
import {
  detailEntityApi as getProjectApi,
  updateEntityApi as modifyProjectApi,
  addEntityApi as addProjectApi,
} from '../../manager/service';
import { queryPageListApi as fetchDatabaseListApi } from '../../database/service';

const FormItem = Form.Item;
const { Option } = Select;

class ProjectInfoForm extends React.Component {
  // const { modalVisible, form, handleEntityUpdate, handleEntityFormModalVisible, entityInfoObj } = props;
  completeCallBack;
  projectId;

  state = {
    visible: false,
    radioDisable: false,
    projectInfo: {},
    databaseList: [],
  };

  componentDidMount() {
    this.props.onRef(this);
  }

  handleModalVisible = (visible, callBack, id) => {
    this.completeCallBack = callBack;
    const { form } = this.props;
    this.setState({
      ...this.state,
      visible: visible,
      radioDisable: id ? true : false,
      projectInfo: {},
    });
    if (visible) {
      // form reset
      form.resetFields();
      this.projectId = id;
      if (id) {
        this.fetchProjectInfo();
      }
      this.fetchDatabaseList();
    }
  };

  handleCancel = () => {
    this.setState({ ...this.state, visible: false });
  };

  fetchProjectInfo = () => {
    getProjectApi(this.projectId).then(res => {
      this.setState({ ...this.state, projectInfo: res.data });
    });
  };

  fetchDatabaseList = () => {
    fetchDatabaseListApi().then(res => {
      this.setState({ ...this.state, databaseList: res.data.rows ? res.data.rows : [] });
    });
  };

  saveProjectInfo = () => {
    let that = this;
    const {
      form: { validateFieldsAndScroll, getFieldsValue },
    } = this.props;
    validateFieldsAndScroll((err, values) => {
      if (!err) {
        let formData = getFieldsValue();
        let doFunName = addProjectApi;
        if (that.projectId) {
          doFunName = modifyProjectApi;
        }
        formData.id = that.projectId;
        /** 数据库关联 */
        formData.dbIds = this.state.projectInfo.dbIds;

        let ret = doFunName(formData);
        ret.then(res => {
          if (that.completeCallBack) {
            that.completeCallBack('add-update');
          }
          that.setState({ ...this.state, visible: false });
        });
      }
    });
  };

  render() {
    const {
      form: { getFieldDecorator },
    } = this.props;
    const formItemLayout = {
      labelCol: {
        sm: { span: 6 },
      },
      wrapperCol: {
        sm: { span: 18 },
      },
    };

    // database list
    let options = [];
    this.state.databaseList.map((value, index) => {
      options.push({ label: value.dbName, value: value.id });
    });

    const { projectInfo, visible, radioDisable } = this.state;

    return (
      <Modal
        width={800}
        visible={visible}
        keyboard={false}
        maskClosable={false}
        title="项目详情"
        onOk={this.handleOk}
        onCancel={this.handleCancel}
        footer={[
          <Button type="primary" key="project_save" onClick={this.saveProjectInfo}>
            保存
          </Button>,
          <Button key="back" onClick={this.handleCancel}>
            关闭
          </Button>,
        ]}
      >
        <Form
          className={styles.form_item_margin_bottom4 + ' ' + styles.form_row_small_margin}
          onSubmit={this.handleSubmit}
        >
          <FormItem {...formItemLayout} label="项目名称">
            {getFieldDecorator('name', {
              initialValue: projectInfo.name,
              rules: [{ required: true, message: '不可为空' }],
            })(<Input className={'ant-col-12'} />)}
            <span className="ant-form-text"> 项目名称(英文字母) </span>
          </FormItem>

          <FormItem {...formItemLayout} label="项目介绍">
            {getFieldDecorator('description', {
              initialValue: projectInfo.description,
              rules: [{ required: true, message: '不可为空' }],
            })(<Input className={'ant-col-12'} />)}
            <span className="ant-form-text"> 项目介绍 </span>
          </FormItem>

          <FormItem {...formItemLayout} label="groupId">
            {getFieldDecorator('groupId', {
              initialValue: projectInfo.groupId,
              rules: [{ required: true, message: '不可为空' }],
            })(<Input className={'ant-col-12'} />)}
            <span className="ant-form-text"> com.test </span>
          </FormItem>

          <FormItem {...formItemLayout} label="artifactId">
            {getFieldDecorator('artifactId', {
              initialValue: projectInfo.artifactId,
              rules: [{ required: true, message: '不可为空' }],
            })(<Input className={'ant-col-12'} />)}
            <span className="ant-form-text"> test_rest </span>
          </FormItem>

          <FormItem {...formItemLayout} label="结构">
            {getFieldDecorator('packageType', {
              initialValue: projectInfo.packageType,
              rules: [{ required: true, message: '不可为空' }],
            })(
              <Radio.Group className="ant-col-12" disabled={radioDisable}>
                <Radio value="standard">standard</Radio>
                <Radio value="module">module</Radio>
              </Radio.Group>,
            )}
            <span className="ant-form-text"> * 结构不可为空</span>
          </FormItem>

          <FormItem {...formItemLayout} label="项目类型">
            {getFieldDecorator('proType', {
              initialValue: projectInfo.proType,
              rules: [{ required: true, message: '不可为空' }],
            })(
              <Radio.Group className="ant-col-12" disabled={radioDisable}>
                <Radio value="micro">微服务</Radio>
                <Radio value="simple">单应用</Radio>
              </Radio.Group>,
            )}
            <span className="ant-form-text"> * 项目类型不可为空</span>
          </FormItem>

          <FormItem {...formItemLayout} label="项目版本">
            {getFieldDecorator('version', {
              initialValue: projectInfo.version,
              rules: [{ required: true, message: '不可为空' }],
            })(<Input className={'ant-col-12'} />)}
            <span className="ant-form-text"> 项目版本 </span>
          </FormItem>

          <FormItem {...formItemLayout} label="访问路径">
            {getFieldDecorator('contextPath', {
              initialValue: projectInfo.contextPath,
              rules: [{ required: true, message: '不可为空' }],
            })(<Input className={'ant-col-12'} />)}
            <span className="ant-form-text"> 访问路径 </span>
          </FormItem>

          <FormItem {...formItemLayout} label="本地路径">
            {getFieldDecorator('localPath', {
              initialValue: projectInfo.localPath,
              rules: [{ required: true, message: '不可为空' }],
            })(<Input className={'ant-col-12'} />)}
            <span className="ant-form-text"> 生成项目本地路径 </span>
          </FormItem>

          <Form.Item label="数据库">
            <Card>
              <Checkbox.Group
                options={options}
                onChange={checkedValues => {
                  projectInfo.dbIds = checkedValues;
                }}
                defaultValue={projectInfo.dbIds}
              />
            </Card>
          </Form.Item>
        </Form>
      </Modal>
    );
  }
}

export default Form.create()(ProjectInfoForm);
